package com.dc.project.util.reader;

import com.dc.project.util.reader.base.BaseReaderUtil;
import com.dc.project.util.reader.base.FileReaderModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;

/**
 * ExcelReaderUtil
 *
 * @author chenxueli
 * @date 2025-03-10 15:41:00
 */
@Slf4j
public class ExcelReaderUtil implements BaseReaderUtil {

    /**
     * 读取文件内容
     *
     * @param file 文件
     * @return 文件内容
     */
    @Override
    public FileReaderModel read(File file) {
        StringBuilder content = new StringBuilder();
        try (FileInputStream fis = new FileInputStream(file)) {
            Workbook workbook;
            if (file.getName().toLowerCase().endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(fis);
            } else if (file.getName().toLowerCase().endsWith(".xls")) {
                workbook = new HSSFWorkbook(fis);
            } else {
                throw new IllegalArgumentException("不支持的Excel文件格式");
            }
            try {
                // 遍历所有sheet
                for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
                    Sheet sheet = workbook.getSheetAt(sheetIndex);
                    if (sheet == null) {
                        continue;
                    }
                    // 添加sheet名称
                    content.append("【").append(sheet.getSheetName()).append("】\n");
                    // 遍历行
                    for (Row row : sheet) {
                        // 遍历单元格
                        for (Cell cell : row) {
                            String cellValue = getCellValueAsString(cell);
                            if (!cellValue.isEmpty()) {
                                content.append(cellValue).append("\t");
                            }
                        }
                        content.append("\n");
                    }
                    content.append("\n");
                }
            } finally {
                workbook.close();
            }
            return FileReaderModel.newInstance(content.toString());
        } catch (Exception e) {
            log.error("读取Excel文件失败：{}", file.getName(), e);
            return FileReaderModel.EMPTY;
        }
    }

    /**
     * 获取单元格的值
     *
     * @param cell 单元格
     * @return 单元格的文本值
     */
    private static String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return "";
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getLocalDateTimeCellValue().toString();
                }
                // 避免数值类型自动转为科学计数法
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                try {
                    return String.valueOf(cell.getNumericCellValue());
                } catch (Exception e) {
                    return cell.getStringCellValue();
                }
            default:
                return "";
        }
    }

}
